import env from "./env";
import xhr from "./xhr";
import plugins from "./plugins";

const mixin = {
  data: () => ({
    loading: false,
    env,
    xhr,
    plugins,
  }),
  computed: {
    profile() {
      return this.plugins.user.profile;
    },
  },
  methods: {
    async nextTick(handle, time) {
      if (time > 0) await new Promise((resolve) => setTimeout(resolve, time));
      return this.$nextTick(handle);
    },
    access(...keys) {
      let debug = this.env.debug;
      let routes = this.$router.options.routes;
      let nodes = this.profile
        ? this.profile.nodes.filter((node) => node.access)
        : [];
      // console.log(this.profile);
      return (
        debug ||
        keys.reduce((count, key) => {
          let route = routes.find(
            (route) => route.name === key || route.path === key
          );
          let access = route
            ? this.access(...route.meta.nodes)
            : nodes.some((node) => node.value === key);
          return access ? count + 1 : count;
        }, 0) === keys.length
      );
    },
  },
  created() {
    this.removeRouterBeforeEach = this.$router.beforeEach((to, from, next) =>
      next(!this.loading)
    );
  },
  destroyed() {
    this.removeRouterBeforeEach();
  },
  beforeRouteEnter(to, from, next) {
    next((inst) =>
      inst.$nextTick(function () {
        window.ss = this.env.debug ? this : null;
        document.title =
          this.$options.title + " - " + this.$root.$options.title;
        document.activeElement.blur();
        this.init();
      })
    );
  },
  beforeRouteUpdate(to, from, next) {
    this.destroy() ? next() + this.init() : next(false);
  },
  beforeRouteLeave(to, from, next) {
    this.destroy() ? next() : next(false);
  },
};

export default mixin;
